﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Data.SqlClient;
using System.Collections.Specialized;

namespace SailHero.Soft.ESB.Client
{
    /// <summary>
    /// _212DataDeal 的摘要说明
    /// 
    /// </summary>
    public class CRC16
    {
        /// <summary>
        /// CRC校验 据赵新杰说是万维的算法
        /// </summary>
        /// <param name="strSource"></param>
        /// <returns></returns>
        public string CRC16_T212(string strSource)
        {
            int hi;
            int i = 0;
            int j = 0;
            int len = 0;
            int crc = 0;
            int tc = 0;
            int sc = 0;
            crc = 0xffff;
            len = strSource.Length;
            string rslt = "";
            foreach (char chr in strSource)
            {
                hi = crc >> 8;
                hi ^= chr;
                crc = hi;
                //tc = crc * (int)(Math.Pow(2, 8));
                ////左移8位
                //crc = (tc ^ crc);
                for (j = 1; j <= 8; j++)
                {
                    sc = crc & 0x1;
                    crc = crc >> 1;
                    if ((sc != 0)) crc = (crc ^ 0xa001);
                }
            }
            rslt = "0000" + crc.ToString("X");
            return rslt.Substring(rslt.Length - 4);
        }
        /// <summary>
        ///  //根据 HJ/T212-2005环境仪器传输标准编写
        /// </summary>
        /// <param name="strSource"></param>
        /// <returns></returns>
        public string CRC16HJ212(string strSource)
        {
            int tmpReg;
            int i, j;

            int CrcReg = 0xffff;
            string rslt = "";
            foreach (char chr in strSource)
            {
                tmpReg = chr;
                tmpReg <<= 8;       //HJ/T212-2005协议标准规定使用高字节进行运算

                CrcReg ^= tmpReg;    //按HJ/T212协议规定是【高字节】参与异或  

                for (i = 0; i < 8; i++)
                {
                    if ((CrcReg & 0x0001) == 1)
                    { //如果即将移出位是1
                        CrcReg >>= 1;        //右移1位 
                        CrcReg ^= 0xa001;    //异或生成多项式 POLY = X^16+X^15+X^2+X+1 
                    }
                    else
                    {         //如果即将移出位是0
                        CrcReg >>= 1;        //只右移,而不异或
                    }
                }
            }
            rslt = "0000" + CrcReg.ToString("X");
            return rslt.Substring(rslt.Length - 4);        //HJ/T212-2005标准要求高位先发送
        }
    }
}